<template>
    <div class="filesDetails pl-20">
        <div class="crumb flex jc-sb aic">
            <div class="flex aic">
                <p v-for="item in pathList" @click="pathData(item)" class="pl-20 cp f14 flex aic"
                    :class="{ 'iconfont icon-Italic': item == '', 'fa5': pathList[pathList.length - 1] == item }">{{
                        item
                    }}<span class="ml-10 f14"
                        :class="{ 'iconfont icon-xiangyoujiantou': pathList[pathList.length - 1] != item }"></span>
                </p>
            </div>
            <div class="w10p">
                <el-input v-model="search" @input="querySearch" placeholder="Type something" :prefix-icon="Search" />
            </div>
        </div>
        <el-table :data="detalisList" @row-click="row" @row-contextmenu="contextmenu" @contextmenu.prevent="rightClick"
            style="width: 100%" height="85vh">
            <el-table-column prop="Title" label="文件名">
                <template v-slot="title">
                    <div class="flex aic">
                        <img v-if="title.row.isfolder != 1" class="titleImg mr-20" :src="title.row.file_path" alt="">
                        <i v-else class="iconfont icon-wenjianleixing-suolvetu-wenjianjia mr-20"></i>
                        <span>{{ title.row.file_or_folder_name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="size" label="大小" />
            <el-table-column prop="upload_time" label="日期" sortable :formatter="formatter" />
        </el-table>
        <!-- 文件上传 -->
        <div class="state pl-10" v-if="state">Are uploading:<span class="ml-5">{{ tempo }}%</span></div>
        <el-upload class="upload-demo" action="http://d-api.files99.com/qmapi/file/input" :on-success="handleChange"
            :on-progress="progress" :on-error="error" :show-file-list="false" :data="data">
            <el-button circle type="primary" size="large" class="add">+</el-button>
        </el-upload>
        <!-- 分享 -->
        <el-dialog v-model="dialogVisible" title="文件分享" width="30%" :before-close="handleClose">
            <div v-if="create">
                <p>文件名：{{ name }}</p>
                <el-radio-group v-model="radio" class="ml-4">
                    <el-radio label="0" size="large">无需密码</el-radio>
                    <el-radio label="1" size="large">通过密码分享</el-radio>
                </el-radio-group>
                <div class="flex aic jc-sb mb-10">
                    <p>到期时间：{{ time }}</p>
                    <el-select v-model="selectDate" @change="selectTime" class="m-2" placeholder="Select">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <div v-if="radio == '1'" class="flex aic">
                    <p>密码：</p>
                    <el-input v-model="password" placeholder="请设置密码" style="width: 90%;"></el-input>
                </div>
            </div>
            <div v-else>
                <div>
                    <div class="flex aic">
                        <p class="w13p">链 接：&nbsp;</p>
                        <span>{{ shareLink }}</span>
                    </div>
                    <div v-if="radio == '1'" class="flex aic mt-10">
                        <p class="w13p">提取码：</p>
                        <span>{{ password }}</span>
                    </div>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">Cancel</el-button>
                    <el-button v-if="create" type="primary" @click="share">
                        创建链接
                    </el-button>
                    <el-button v-else type="primary" @click="copy">
                        复制并关闭
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, shallowRef, onMounted, watch } from 'vue'
import * as $axios from '../../../api/index'
import { ElMessage } from 'element-plus'
import { menusEvent } from 'vue3-menus';  //鼠标右键功能菜单
import useClipboard from 'vue-clipboard3';
import { useDemoStore } from '../../../pinia/index'
import { Search } from '@element-plus/icons-vue'
const store = useDemoStore()
const { toClipboard } = useClipboard(); //剪切板

const props = defineProps({
    detalisList: Array,
    userId: String
})

// 排序
// const formatter = (row, column) => {
//     // console.log(row)
//     return row.address
// }


// 点击面包屑触发
const pathData = (value) => {
    // console.log(props.userId != '')
    if (value == '' && props.userId == '') {
        emits('root')
    }else if(arrs.value.UserGroupName == value){
        emits('userList', arrs.value.user)
    }else if(storeName.value.file_or_folder_name == value){
        storeValue.value = storeName.value
        row()
    }else if(props.userId != ''){
        path.value = value
        getTable()
    } 
    // console.log(storeName.value)
    const index = pathList.value.findIndex(item => {
        return item == value
    })
    pathList.value.splice(index + 1, 10)  //删除指定元素后面的元素
}

// 当列表某一行被点击时会触发该事件
const pathList = ref([''])
const path = ref('')
const id = ref('')
const arrs = ref([])
const storeValue = ref({})
const storeName = ref({})
const row = (value) => {
    storeValue.value = value || storeValue.value
    // console.log(storeValue.value)
    if (storeValue.value.send == "no") {
        props.detalisList.forEach(item => {
            if (item.UserGroupName == storeValue.value.UserGroupName) {
                arrs.value = storeValue.value
                emits('userList', item.user)
                pathList.value.push(storeValue.value.file_or_folder_name)
                // console.log(arrs.value)
            }
        })
    } else if (storeValue.value.send == "yes" || storeValue.value.isfolder == 1) {
        // console.log(storeValue.value)
        storeValue.value.send == "yes" ? storeName.value = storeValue.value :''
        path.value = storeValue.value.send == undefined ? storeValue.value.file_or_folder_name : ''
        id.value = storeValue.value.id || storeValue.value.user_id || id.value
        getTable()
        pathList.value.push(storeValue.value.file_or_folder_name)
    }
    data.value.path = path.value
}

const clear = ()=>{
    pathList.value = ['']  //展开菜单就清空数组
}
defineExpose({  //暴露方法
    clear
})

// 文件数据
const getTable = () => {
    const data = {
        token: store.token,
        user_open_id: id.value,
        path: path.value
    }
    $axios.$fileGet(data).then(res => {
        res.data.forEach(item => {
            item.size = item.size ? (item.size / 1024 / 1000).toFixed(2) + 'M' : '暂无数据'
        })
        // console.log(res.data)
        emits('userList', res.data)
    })
}

const emits = defineEmits(['userList', 'root'])


// 鼠标右键触发
const file_path = ref() //下载链接
const name = ref()
const isfolder = ref(1)  //文件类别
const files_id = ref()  //文件id
const contextmenu = (value) => {
    file_path.value = value.file_path
    name.value = value.file_or_folder_name
    files_id.value = value.files_id
    isfolder.value = value.isfolder || 0
    console.log(value)
}

// 右键触发，弹出菜单
const rightClick = (event) => {
    if (isfolder.value == 0) { //如果是文件夹就不给调出菜单
        menusEvent(event, menus.value);
        event.preventDefault();
    }
}
const menus = shallowRef({
    menus: [
        {
            label: "下载",
            icon: '<i class="iconfont icon-xiazai"></i>',
            tip: ' ',
            click: () => {
                down()
            }
        },
        {
            label: "分享",
            icon: '<i class="iconfont icon-fenxiang"></i>',
            tip: '',
            click: () => {
                dialogVisible.value = true
                create.value = true
                selectTime()
            }
        },
        // {
        //     label: "删除",
        //     icon: '<i class="iconfont icon-shanchu"></i>',
        //     tip: '',
        //     click: () => {
        //         console.log(131)
        //     }
        // },
    ]
});

// 下载图片
const down = () => {
    const data = {
        token: store.token,
        file: files_id.value
    }
    $axios.$fileDown(data).then(res => {
        // console.log(res)
        var base64 = res.data.base.toString(); // imgSrc 就是base64哈
        var byteCharacters = atob(
            base64.replace(/^data:image\/(png|jpeg|jpg);base64,/, "")
        );
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: undefined,
        });
        var aLink = document.createElement("a");
        aLink.download = name.value; //这里写保存时的图片名称
        aLink.href = URL.createObjectURL(blob);
        aLink.click();
    })
}


// 分享弹窗
const dialogVisible = ref(false)
// 单选框
const radio = ref('0')

// 到期时间
const time = ref()
// 设置过期时间
const selectDate = ref(1)
const options = [
    {
        label: '一小时过期',
        value: 1
    },
    {
        label: '一周过期',
        value: 2
    },
    {
        label: '一个月过期',
        value: 3
    },
    {
        label: '半年过期',
        value: 4
    },
    {
        label: '一年过期',
        value: 5
    },
]
// 获取过期时间
const selectTime = (value) => {
    const data = {
        token: store.token,
        type: value || 1
    }
    $axios.$fileGet_time(data).then(res => {
        time.value = res.data.time
        // console.log(res.data)
    })
}

watch(radio, (value) => {
    if (value == 1) {
        random(1000, 9000)
    } else {
        password.value = ''
    }
})

// 提取码输入框
const password = ref('')
function random(num1, num2) {  //生成随机数
    var text = Math.random() * (num2 - num1) + num1
    password.value = Math.round(text)
}

// 分享按钮
const create = ref(true)
const shareLink = ref() //分享链接
const share = () => {
    const data = {
        token: store.token,
        path: name.value,
        expiration_time: time.value,
        pwd: password.value
    }
    if (radio.value == '0') {  //正常分享
        $axios.$fileShare(data).then(res => {
            if (res.Status == 0) {
                create.value = false
                shareLink.value = res.data.share_customer
                console.log(res)
            }
        })
    } else {  //通过密码分享
        $axios.$filePassword_share(data).then(res => {
            if (res.Status == 0) {
                create.value = false
                shareLink.value = res.data.share_customer
                console.log(res)
            }
        })
    }
}

// 复制并关闭
const copy = async () => {
    dialogVisible.value = false
    const pas = password.value ? '提取码' + password.value : ''
    try {
        await toClipboard('链接：' + shareLink.value + ' ' + pas)
    } catch (e) {
        console.error(e)
    }
    ElMessage({
        message: 'Copy success',
        type: 'success',
    })
}


// 搜索
const search = ref('')
var timer;
const querySearch = (name) => {
    const data = {
        token: store.token,
        name: name
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        $axios.$fileFind(data).then(res => {
            emits('userList', res.data)
            console.log(res.data)
        })
    }, 300)
}




// 文件上传参数
const data = ref({
    token: store.token,
    path: path.value
})

// 上传时执行的钩子
const state = ref(false)
const tempo = ref('')
const progress = (value) => {
    tempo.value = value.percent.toFixed(0)
    state.value = true
    // console.log(value.percent)
}

// 上传成功执行的钩子
const handleChange = (value) => {
    state.value = false
    getTable()
    ElMessage({
        message: 'upload successful',
        type: 'success',
    })
    // console.log(value)
}

// 上传失败执行的钩子
const error = (value) => {
    state.value = false
    ElMessage({
        message: 'Upload failed',
        type: 'warning',
    })
    console.log(value)
}

</script>

<style lang="less" scoped>
@import '../files.less';

.brs {
    border-radius: 10px;
}
</style>